import { Button, StyleSheet, Text, View, ScrollView } from 'react-native';
import React, { useRef, useState } from 'react';
import {
  Camera,
  useCameraDevice,
  useCameraFormat,
  useCameraPermission,
} from 'react-native-vision-camera';
import { CameraRoll } from '@react-native-camera-roll/camera-roll';

type PathTestCase = {
  id: number;
  title: string;
  description: string;
  options: { path?: string };
  expected: 'SUCCESS' | 'FAILURE';
};

export function VideoTest() {
  const device = useCameraDevice('back');
  const { hasPermission, requestPermission } = useCameraPermission();
  const camera = useRef<Camera>(null);
  const format = useCameraFormat(device, [
    { videoResolution: { width: 1920, height: 1080 } },
    { fps: 30 },
  ]);

  if (!device) {
    return <Text>No Camera Device Found</Text>;
  }

  if (!hasPermission) {
    requestPermission();
  }

  const [videoHdr, setVideoHdr] = useState(false);
  const [startStatus, setStartStatus] = useState<'end' | 'start' | 'pause'>('end');
  const [videoFile, setVideoFile] = useState<string>('');
  const [videoPath, setVideoPath] = useState<string>('');
  const [activeTest, setActiveTest] = useState<PathTestCase | null>(null);

  const testCases: PathTestCase[] = [
    {
      id: 1,
      title: "1. 默认路径",
      description: "不提供path参数，使用系统临时目录",
      options: {},
      expected: 'SUCCESS'
    },
    {
      id: 2,
      title: "2. 绝对目录路径",
      description: "传入绝对目录路径（需真实存在）",
      options: { path: "/data/storage/el2/base/haps/entry/files/" },
      expected: 'SUCCESS'
    },
    {
      id: 3,
      title: "3. 沙箱不存在的路径",
      description: "传入不存在的路径",
      options: { path: "/data/storage/el2/base/1122334455667788" },
      expected: 'SUCCESS'
    },
    {
      id: 4,
      title: "4. 文件路径格式",
      description: "传入包含文件名的路径",
      options: { path: "/data/storage/el2/base/haps/entry/files/video.mp4" },
      expected: 'SUCCESS'
    },
    {
      id: 5,
      title: "5. 空路径",
      description: "传入空字符串路径",
      options: { path: "" },
      expected: 'FAILURE'
    },
    {
      id: 6,
      title: "6. 多斜杠路径",
      description: "传入多个///目录",
      options: { path: "/data/storage/el2/base////////files/" },
      expected: 'SUCCESS'
    },
    {
      id: 7,
      title: "7. 特殊字符路径",
      description: "路径包含中文和特殊字符",
      options: { path: "/data/storage/el2/base/测试/@#$%^&/" },
      expected: 'SUCCESS'
    },
    {
      id: 8,
      title: "8. 超长路径名",
      description: "路径长度超过系统限制",
      options: {
        path: "/data/storage/el2/base/" + "a".repeat(240) + "/"
      },
      expected: 'SUCCESS'
    },
    {
      id: 9,
      title: "9. 带空格路径",
      description: "路径包含空格字符",
      options: { path: "/data/storage/el2/base/My Videos/" },
      expected: 'SUCCESS'
    },
  ];

  const onStart = async (testCase?: PathTestCase) => {
    setVideoPath('');
    setVideoFile('');
    setStartStatus('start');

    const recordingOptions = {
      fileType: 'mp4' as const,
      videoCodec: 'h265' as const,
      videoBitRate: 'normal' as const,
      videoHdr,
      onRecordingError: (error: any) => {
        setStartStatus('end');
        setVideoFile(`❌ 录制失败: ${error.message}`);
      },
      onRecordingFinished: (video: any) => {
        setStartStatus('end');
        if (video?.path) {
          setVideoPath(video.path);
          const result = testCase
            ? testCase.expected === 'SUCCESS'
              ? '✅ 录制成功 (符合预期)'
              : '⚠️ 录制成功 (预期失败)'
            : '✅ 录制成功';
          setVideoFile(`${result}\n路径: ${video.path}`);
        }
      },
    };

    try {
      if (testCase) {
        setActiveTest(testCase);
        await camera.current?.startRecording({
          ...recordingOptions,
          ...testCase.options
        });
      } else {
        setActiveTest(null);
        await camera.current?.startRecording(recordingOptions);
      }
    } catch (error) {
      setStartStatus('end');
      setVideoFile(`❌ 开始录制失败: ${error.message}`);
    }
  };

  const onPause = () => {
    setStartStatus('pause');
    camera.current?.pauseRecording();
  };

  const onStop = async () => {
    try {
      await camera.current?.stopRecording();
      await new Promise(resolve => setTimeout(resolve, 300));
    } catch (error) {
    }
    setStartStatus('end');
  };

  const onResume = () => {
    setStartStatus('start');
    camera.current?.resumeRecording();
  };

  const toggleHdr = () => setVideoHdr(!videoHdr);

  const saveToGallery = () => {
    if (!videoPath) return;

    CameraRoll.saveAsset(videoPath)
      .then(() => {
        setTimeout(() => {
          setVideoPath('');
          setVideoFile('');
        }, 500);
      })
      .catch(error => {
        setVideoFile(`❌ 保存失败: ${error.message}`);
      });
  };

  return (
    <View style={styles.container}>
      <Camera
        style={styles.cameraPreview}
        ref={camera}
        isActive={true}
        device={device}
        video={true}
        audio={false}
        videoHdr={videoHdr}
        fps={30}
        format={format}
        onError={error => console.log(error.message)}
      />

      <View style={styles.controlPanel}>
        <ScrollView
          horizontal
          style={styles.testCasesContainer}
          showsHorizontalScrollIndicator={false}
        >
          {testCases.map(test => (
            <View key={test.id} style={styles.testCaseButton}>
              <Button
                title={test.title}
                onPress={() => onStart(test)}
                color={activeTest?.id === test.id ? '#4CAF50' : '#2196F3'}
              />
            </View>
          ))}
        </ScrollView>

        {activeTest && (
          <View style={styles.testInfo}>
            <Text style={styles.testTitle}>{activeTest.title}</Text>
            <Text style={styles.testDescription}>{activeTest.description}</Text>
          </View>
        )}

        <View style={styles.controlButtons}>

          {startStatus === 'start' ? (
            <Button title="暂停" onPress={onPause} />
          ) : null}

          {startStatus === 'pause' ? (
            <Button title="继续" onPress={onResume} />
          ) : null}

          {startStatus !== 'end' ? (
            <Button title="停止" onPress={onStop} color="#FF0000" />
          ) : null}
        </View>

        {videoFile ? (
          <View style={styles.resultContainer}>
            <Text style={styles.resultText}>{videoFile}</Text>
            {videoPath ? (
              <Button title="保存到相册" onPress={saveToGallery} />
            ) : null}
          </View>
        ) : null}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
  },
  cameraPreview: {
    height: 300,
    flex: 1,
  },
  controlPanel: {
    padding: 12,
  },
  testCasesContainer: {
    marginBottom: 10,
  },
  testCaseButton: {
    marginRight: 8,
    minWidth: 100,
  },
  testInfo: {
    marginBottom: 10,
    padding: 10,
    backgroundColor: 'rgba(255,255,255,0.1)',
    borderRadius: 5,
  },
  testTitle: {
    color: '#2196F3',
    fontWeight: 'bold',
    fontSize: 14,
  },
  testDescription: {
    color: '#FFF',
    fontSize: 12,
  },
  controlButtons: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 10,
    flexWrap: 'wrap',
    gap: 10,
  },
  resultContainer: {
    padding: 10,
    backgroundColor: 'rgba(255,255,255,0.1)',
    borderRadius: 5,
  },
  resultText: {
    color: '#FFF',
    marginBottom: 10,
  },
});